<?php
/**
 * Created by PhpStorm.
 * User: clcw908
 * Date: 2016/12/21
 * Time: 14:26
 */
date_default_timezone_set("Asia/Shanghai");
set_time_limit(0);
if (isset($_SERVER['REQUEST_URI'])) {
	die('error');
}

if (!defined('API_ROOT_PATH')) {
	define('API_ROOT_PATH', dirname(__FILE__));
}

require(API_ROOT_PATH . '/../inc/common.php');
require(API_ROOT_PATH . '/../inc/Config.php');
require(API_ROOT_PATH . '/../inc/MysqliDb.php');

//初始化数据库链接
function init_db()
{
	$db = new MysqliDb ([
		'host' => MYSQLDB,
		'username' => MYSQLDB_USER,
		'password' => MYSQLDB_PWD,
		'db' => MYSQLDB_DATABASE,
		'port' => 3306,
		'prefix' => 'au_',
		'charset' => 'utf8'
	]);
	return $db;
}
$db = init_db();

while (true){
	$sql = "select po.id,po.order_id,po.car_id,po.amount,pl.bank_account,pl.emp_id,pl.createtime,pl.pay_type,pl.last_update,pl.status from au_purchase_order po INNER JOIN au_pay_log pl 
		ON po.order_id = pl.order_id where po.id not in(select po_id from au_purchase_payments) and pl.status=0";
	$data = $db->query($sql);
	foreach ($data as $key=>$val){
		$db->startTransaction();
		$bank_account = $val['bank_account'];
		$accountData = json_decode($bank_account,true);
		//print_r($val);
		if($accountData){
			$paymentData['bank_name'] = $accountData['bank_name'];
			$paymentData['account_name'] = $accountData['account_name'];
			$paymentData['card_no'] = $accountData['card_no'];
		}else{
			$orderId = $val['order_id'];
			$signData = $db->where('order_id',$orderId)->getOne('signature_log');
			$paymentData['bank_name'] = $signData['deposit_bank'];
			$paymentData['account_name'] = $signData['payee_name'];
			$paymentData['card_no'] = $signData['payee_account'];
		}
		$carInfo = $db->where('car_id',$val['car_id'])->getOne('cars');
		if($val['pay_type'] == 1){ //首款
			$carSource = $carInfo['car_source'];
			if($carSource == 1){ //如果是4s车源
				$paymentData['pay_type'] = 1;
				$paymentData['amount'] = $val['amount']; //100%的全款
			}else{
				$threeInOne = $carInfo['three_in_one']; //三证合一
				if($threeInOne == 1){
					$paymentData['pay_type'] = 2; //应付车主（首）
					$paymentData['amount'] = $val['amount']/2;
				}
				if($threeInOne == 2){
					$db->rollback();
					logUtil('车源'.$carInfo['sid'].'个人车源，三证不合一的，不应该有首付款信息。拍单号：'.$val['order_id']);
					die();
				}
			}
		}else{ //尾款
			$carSource = $carInfo['car_source'];
			if($carSource == 1){ //如果是4s车源
				$db->rollback();
				logUtil('车源'.$carInfo['sid'].'4s车源，不应该有尾款信息。拍单号：'.$val['order_id']);
				die();

			}else{
				$threeInOne = $carInfo['three_in_one']; //三证合一
				if($threeInOne == 1){
					$paymentData['pay_type'] = 3; //应付车主（尾）
					$paymentData['amount'] = $val['amount']/2;
				}
				if($threeInOne == 2){
					$paymentData['pay_type'] = 3; //应付车主（尾）
					$paymentData['amount'] = $val['amount']; //100%的全款
				}
			}
		}

		if($val['status'] == 2){ //如果是关闭的，那就生成一张作废的付款单
			$val['status'] = 3;
		}

		$paymentData['status'] = $val['status'];
		$paymentData['pay_way'] = 2;
		$paymentData['create_time'] = $val['createtime'];
		if($val['status'] == 1){
			$paymentData['update_time'] = $val['last_update'];
		}
		$paymentData['emp_id'] = $val['emp_id'];
		$paymentId = generatorPayment($paymentData);
		if(!$paymentId){
			$db->rollback();
			logUtil('采购单：'.$val['id'].'生成付款单失败');
			die();
		}

		$result = addPaymentRelation($val['id'],$paymentId,'1');
		if(!$result){
			$db->rollback();
			logUtil('采购单：'.$val['id'].'生成付款单关系失败');
			die();
		}
		logUtil('采购单：'.$val['id'].'生成付款单及关系成功');
		$db->commit();
	}
	logUtil('生成完成');exit();
}
//$db->where()->


/**
 *  生成付款单
 *
 * @param $paymentData 付款单数据
 * @return mixed
 */
function generatorPayment($paymentData)
{
	global $db;
	$payment_no = genBillsNo("FK", $paymentData['pay_type'] , $paymentData['create_time']);
	$paymentData['payment_no'] = $payment_no;
	if($paymentData['emp_id']){
		$employData = $db->where('emp_id',$paymentData['emp_id'])->getOne('employee');
		$paymentData['emp_name'] = $employData['real_name'];
	}else{
		$paymentData['emp_id'] = '';
		$paymentData['emp_name'] = '';
	}

	$result = $db->insert("payment",$paymentData);
	if(!$result){
		var_dump($result);
		var_dump($db->getLastQuery());die();
	}
	return $result;
}

/**
 * 添加采购单付款关系数据
 *
 * @param int $purchaseOrderId 采购单编号
 * @param int $paymentId 付款单编号
 * @param int $paymentType 付款类型
 * @return mixed
 */
function addPaymentRelation($purchaseOrderId, $paymentId, $paymentType)
{
	global $db;
	$data = [
		'po_id' => $purchaseOrderId,
		'payment_id' => $paymentId,
		'pay_type' => $paymentType,
		'createtime' => date('Y-m-d H:i:s', time()),
	];
	$result = $db->insert('purchase_payments',$data);
	if(!$result){
		var_dump($result);
		var_dump($db->getLastQuery());die();
	}
	return $result;
}

/**
 * 产生一个单据编号
 * @param $type
 * @param $subType
 * @param $date
 * @return string
 */
function genBillsNo($type, $subType, $date)
{
	global $db;
	if ($subType < 10) $subType = "0" . $subType;
	if($date != '0000-00-00 00:00:00'){
		$date = date("Ymd",strtotime($date));
	}else{
		$date = date("Ymd",time());
	}
	$orderNo = $type . $subType . $date . gen4Chars();
	if($type == 'CG'){ //如果是采购单
		$data = $db->where('purchase_order_nu',$orderNo)->getOne('purchase_order');
		if($data){
			return genBillsNo($type, $subType, $date);
		}
	}elseif($type == 'FK')//如果是付款单
	{
		$data = $db->where('payment_no',$orderNo)->getOne('payment');
		if($data){
			return genBillsNo($type, $subType, $date);
		}
	}elseif ($type == 'SK'){
		$data = $db->where('collection_no',$orderNo)->getOne('collection');
		if($data){
			return genBillsNo($type, $subType, $date);
		}
	}
	return $orderNo;
}


/**
 * 产生固定长度的随机字符串
 * @param $len
 * @param null $chars
 * @return string
 */
function genRandomChars($len, $chars = null)
{
	if (is_null($chars)) {
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	}
	mt_srand(10000000 * (double)microtime());
	for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) {
		$str .= $chars[mt_rand(0, $lc)];
	}
	return $str;
}

/**
 * 产生一个四位的随机字符串
 * @return string
 */
function gen4Chars()
{
	$strChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	$numbers = "0123456789";
	$randomString = genRandomChars(3);
	if (ctype_digit($randomString)) {
		$randomString = $randomString . genRandomChars(1, $strChars);
	} elseif (ctype_alpha($randomString)) {
		$randomString = $randomString . genRandomChars(1, $numbers);
	} else {
		$randomString = $randomString . genRandomChars(1);
	}
	return $randomString;
}